#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import codecs
import os
import json

# from pdfminer.pdfparser import PDFParser, PDFDocument
# from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
# from pdfminer.converter import PDFPageAggregator
# from pdfminer.layout import LTTextBoxHorizontal, LAParams
# from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
from io import open
# from docx import Document
from pyquery import PyQuery as pyq

# 从文件中读取数据到对应的数据结构中

READ_INSERT_SPACE = 1

"""
读取模式
按行读取数据
"""
READ_LINE = 1

"""
读取模式
按行读取数据
保存为LIST
"""
READ_LINE_LIST = 2

"""
读取模式
按某个字符串分割
"""
READ_SPLIT = 3

"""
读取模式
按某个字符串分割
第一个字符串作为key
后面的字符串以list形式存储
"""
READ_SPLIT_LIST = 4

"""
读取模式
按照正则分割
"""
READ_SPLIT_RE = 5

"""
读取模式
读取全文模式
"""
READ_ALL = 6

"""
读取模式
按行读取 
以某个字符分割
保存成list
"""
READ_LIST = 7

UNLIMITED_COUNT = -1


# def read_file_to_list(path, encoding='utf-8'):
#     lines = codecs.open(path, 'r', encoding)
#     l = []
#     for line in lines:
#         line = line.strip()
#         l.append(line)
#     return l
#
#
# def read_file_to_dict(path, encoding='utf-8'):
#     result = {}
#     file_names = os.listdir(path)
#     for file in file_names:
#         tmp = ''
#         p = path + '/' + file
#         lines = codecs.open(p, 'r', encoding)
#         for line in lines:
#             tmp += line.strip()
#         result[file] = tmp
#     return result
#
#
# def read_file_to_set(path, encoding='utf-8'):
#     lines = codecs.open(path, 'r', encoding)
#     result = set()
#     for line in lines:
#         result.add(line.strip())
#     return result
#     pass
#
#
# def read_file(path, mod=READ_INSERT_SPACE, encoding='utf-8'):
#     lines = codecs.open(path, 'r', encoding)
#     result = ''
#     for line in lines:
#         result += line.strip()
#         if mod == READ_INSERT_SPACE:
#             result += ' '
#     return result
#     pass
#
#
# def read_result(path, encoding='utf-8'):
#     lines = codecs.open(path, 'r', encoding)
#     result = {}
#     for line in lines:
#         tmp = line.strip().split(' ', 2)
#         if len(tmp) == 1:
#             result[tmp[0]] = ''
#             pass
#         else:
#             result[tmp[0]] = tmp[1]
#             pass
#         pass
#     return result
#     pass


# 在此之前的方法暂时弃用

def read(path, mod=READ_LINE, split_symbol=' ', count=2, use_file_key=True, encoding='utf-8'):
    """
    TODO 完善该方法
    做成通用的文件读取方法
    读取文件内容
    以字典的形式返回
    若为目录
    则key为目录名 value为对应的目录下的内容
    若为文件
    则key为文件名 value为对应内容下的内容
    :param path: 文件路径
    :param mod: 读取模式
    :param split_symbol: 分割的符号
    :param count: 分割的次数
    :param use_file_key: 是否使用文件名作为key值
    :param encoding: 编码
    :return:
    """
    results = {}
    if os.path.isfile(path):
        # 读取文件
        rs = _read(path, mod, split_symbol, count, encoding)
        if use_file_key is True:
            results[os.path.basename(path)] = rs
            pass
        else:
            results = rs
            pass
        return results
        pass
    path_list = os.listdir(path)
    for file_name in path_list:
        p = path + '/' + file_name
        # p为目录 则递归读取
        rs = read(p, mod, split_symbol, count, use_file_key, encoding)
        results[file_name] = rs
        pass
    return results
    pass


def _read(path, mod=READ_LINE, split_symbol=' ', count=2, encoding='utf-8'):
    results = {} if mod != READ_ALL else ''
    results = [] if mod == READ_LINE_LIST else results
    if mod == READ_SPLIT_RE:
        import re
        p = re.compile(split_symbol)
        pass
    lines = codecs.open(path, 'r', encoding)
    cnt = 0
    # TODO 后期改进 将if判断放在for循环外
    for line in lines:
        content = line.strip()
        if content == '':
            continue
            pass
        if mod == READ_LINE:
            results[cnt] = content
            pass
        if mod == READ_LINE_LIST:
            results.append(content)
            pass
        if mod == READ_SPLIT:
            tmp = content.split(split_symbol, count)
            if len(tmp) < 2:
                continue
                pass
            if len(tmp) == 2:
                results[tmp[0]] = tmp[1]
                pass
            else:
                key = tmp[0]
                del tmp[0]
                results[key] = tmp
                pass
            pass
        if mod == READ_SPLIT_LIST:
            tmp = content.split(split_symbol, count)
            key = tmp[0]
            del tmp[0]
            results[key] = tmp
            pass
        if mod == READ_ALL:
            results += line
            pass
        if mod == READ_LIST:
            results[cnt] = content.split(split_symbol, count)
            pass
        if mod == READ_SPLIT_RE:
            tmp = p.split(content, count)
            key = tmp[0]
            del tmp[0]
            if len(tmp) == 1:
                results[key] = tmp[0]
                pass
            else:
                results[key] = tmp
                pass
            pass
        cnt += 1
        pass
    return results
    pass


def read_dict(path, split_symbol=' ', encoding='utf-8'):
    return _read(path, READ_SPLIT, split_symbol, 2, encoding)
    pass


def read_list_to_dict(path, value=1, encoding='utf-8'):
    l = _read(path, READ_LINE_LIST, ' ', 2, encoding)
    results = {}
    for t in l:
        results[t] = value
        pass
    return results
    pass


def read_pdf(path):
    try:
        return _read_pdf(path)
    except:
        return ''
    pass


def _read_pdf(path):
    fp = open(path, 'rb')  # 以二进制读模式打开
    # 用文件对象来创建一个pdf文档分析器
    praser = PDFParser(fp)
    # 创建一个PDF文档
    doc = PDFDocument()
    # 连接分析器 与文档对象
    praser.set_document(doc)
    doc.set_parser(praser)

    # 提供初始化密码
    # 如果没有密码 就创建一个空的字符串
    doc.initialize()

    # 检测文档是否提供txt转换，不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 创建PDf 资源管理器 来管理共享资源
        rsrcmgr = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        # 创建一个PDF解释器对象
        interpreter = PDFPageInterpreter(rsrcmgr, device)
        results = ''
        # 循环遍历列表，每次处理一个page的内容
        for page in doc.get_pages():  # doc.get_pages() 获取page列表
            interpreter.process_page(page)
            # 接受该页面的LTPage对象
            layout = device.get_result()
            for x in layout:
                if (isinstance(x, LTTextBoxHorizontal)):
                    if hasattr(x, 'get_text'):  # 因为文档中不只有text文本
                        results += x.get_text()
                        pass
                    pass
                pass
            pass
        pass
    return results
    pass


def read_doc(path):
    try:
        doc = Document(path)
        result = ''
        for para in doc.paragraphs:
            result += para.text
            pass
        return result
    except Exception as e:
        print(e)
        return ''
    pass


def read_html(path):
    with open(path, encoding='utf-8') as file:
        contents = file.read()
        doc = pyq(contents)
        contents = doc('body').text()
        return contents
        pass
    pass


def read_json(path):
    with open(path) as file:
        results = json.load(file)
        return results
        pass
    pass
